<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NTag } from 'naive-ui';
import { fetchBatchDeleteUser, fetchDeleteUser, fetchGetUserList } from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { genderRecord } from '@/constants/business';
import { useTable, useTableOperate } from '@/hooks/common/table';
import ShowDetailModal from '@/views/manage/user/modules/show-detail-modal.vue';
import UserOperateModal from './modules/user-operate-modal.vue';
import UserSearch from './modules/user-search.vue';

const appStore = useAppStore();

const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: fetchGetUserList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    status: null,
    userName: null,
    displayName: null,
    gender: null,
    nickName: null,
    telephone: null,
    email: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 48
    },
    {
      key: 'userName',
      title: $t('page.manage.user.userName'),
      align: 'center',
      minWidth: 60,
      width: 90
    },
    {
      key: 'gender',
      title: $t('page.manage.user.gender'),
      align: 'center',
      width: 60,
      render: (row: any) => {
        if (row.gender === null) {
          return null;
        }

        const tagMap: Record<Api.SystemManage.gender, NaiveUI.ThemeColor> = {
          1: 'primary',
          0: 'error'
        };

        const label = $t(genderRecord[row.gender as Api.SystemManage.gender]);

        return <NTag type={tagMap[row.gender as Api.SystemManage.gender]}>{label}</NTag>;
      }
    },
    {
      key: 'nickName',
      title: $t('page.manage.user.nickName'),
      align: 'center',
      minWidth: 60,
      width: 90
    },
    {
      key: 'displayName',
      title: $t('page.manage.user.displayName'),
      align: 'center',
      minWidth: 60,
      width: 90
    },
    {
      key: 'telephone',
      title: $t('page.manage.user.telephone'),
      align: 'center',
      width: 100
    },
    {
      key: 'email',
      title: $t('page.manage.user.email'),
      align: 'center',
      minWidth: 120,
      width: 160
    },
    /*    {
      key: 'status',
      title: $t('page.manage.user.status'),
      align: 'center',
      width: 60,
      render: row => {
        if (row.status === null) {
          return null;
        }

        const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
          1: 'success',
          0: 'warning'
        };

        const label = $t(enableStatusRecord[row.status]);

        return <NTag type={tagMap[row.status]}>{label}</NTag>;
      }
    }, */
    {
      key: 'status',
      title: $t('page.manage.user.status'),
      align: 'center',
      width: 60,
      render: (row: any) => {
        if (row.status === null) {
          return null;
        }

        const switchMap: Record<Api.Common.EnableStatus, boolean> = {
          1: true,
          2: false
        };
        return <n-switch v-model:value={switchMap[row.status as Api.Common.EnableStatus]} disabled />;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      render: (row: any) => (
        <div class="flex-center gap-8px">
          <NButton type="info" ghost size="small" onClick={() => showDetail(row.id)}>
            {$t('common.detail')}
          </NButton>

          <NButton type="primary" ghost size="small" onClick={() => handleEditUser(row.id)}>
            {$t('common.edit')}
          </NButton>
          <NButton type="error" ghost size="small" onClick={() => showDeleteConfirm(row.id)}>
            {$t('common.delete')}
          </NButton>
        </div>
      )
    }
  ]
});

const {
  modalVisible,
  operateType,
  editingData,
  modalFormData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted,
  onShowDetail
  // closeDrawer
} = useTableOperate(data, getData);

// 用户操作弹窗的可见性状态
const userOperateModalVisible = ref(false);

// 处理新增用户
function handleAddUser() {
  handleAdd();
  userOperateModalVisible.value = true;
}

// 处理编辑用户
function handleEditUser(id: number) {
  // 找到对应的用户数据
  const userData = (data.value as any[]).find(item => item.id === id);
  if (userData) {
    editingData.value = userData;
    operateType.value = 'edit';
    userOperateModalVisible.value = true;
  }
}

// 用户操作提交后的回调
function onUserOperateSubmitted() {
  userOperateModalVisible.value = false;
  getData();
}

async function handleBatchDelete() {
  try {
    const { error } = await fetchBatchDeleteUser(checkedRowKeys.value.map(key => Number(key)).filter(id => !Number.isNaN(id)));

    if (!error) {
      window.$message?.success($t('common.deleteSuccess'));
      await onBatchDeleted();
    } else {
      window.$message?.error($t('common.operationFailed'));
    }
  } catch (err) {

    window.$message?.error($t('common.operationFailed'));
  }
}

async function handleDelete(id: number) {
  try {
    const { error } = await fetchDeleteUser(id);

    if (!error) {
      window.$message?.success($t('common.deleteSuccess'));
      await onDeleted();
    } else {
      window.$message?.error($t('common.operationFailed'));
    }
  } catch (err) {

    window.$message?.error($t('common.operationFailed'));
  }
}

// 显示删除确认对话框
function showDeleteConfirm(id: number) {
  window.$dialog?.warning({
    title: $t('common.tip'),
    content: $t('common.confirmDelete'),
    positiveText: $t('common.confirm'),
    negativeText: $t('common.cancel'),
    onPositiveClick: () => {
      handleDelete(id);
    }
  });
}

function edit(id: number) {
  handleEdit(id);
}

// 打开详情 弹窗
function showDetail(id: number) {
  onShowDetail(id);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <UserSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getData" />
    <NCard :title="$t('page.manage.user.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :show-delete="true"
          :loading="loading"
          @add="handleAddUser"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :single-line="false"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <ShowDetailModal v-model:visible="modalVisible" :row-data="modalFormData" />

      <UserOperateModal
        v-model:visible="userOperateModalVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="onUserOperateSubmitted"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
